<template>
  <div class="register-container">
    <h2>注册</h2>
    <el-form
      class="elForm"
      :model="registerForm"
      ref="registerFormRef"
      label-width="auto"
    >
      <el-form-item
        label="用户名"
        prop="username"
        :rules="[{ required: true, message: '请输入用户名', trigger: 'blur' }]"
      >
        <el-input v-model="registerForm.username" />
      </el-form-item>
      <el-form-item
        label="邮箱"
        prop="email"
        :rules="[
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
        ]"
      >
        <el-input v-model="registerForm.email" />
      </el-form-item>
      <el-form-item
        label="密码"
        prop="password"
        :rules="[{ required: true, message: '请输入密码', trigger: 'blur' }]"
      >
        <el-input v-model="registerForm.password" type="password" />
      </el-form-item>
      <el-form-item
        label="确认密码"
        prop="confirmPassword"
        :rules="[
          { required: true, message: '请确认密码', trigger: 'blur' },
          { validator: validatePassword, trigger: 'blur' }
        ]"
      >
        <el-input v-model="registerForm.confirmPassword" type="password" />
      </el-form-item>
      <el-button class="registerBut" type="primary" @click="register"
        >注册</el-button
      >
    </el-form>
    <div class="login-link">
      <router-link to="/login">已有账号？点击登录</router-link>
    </div>
  </div>
</template>

<script setup>
import { ref, getCurrentInstance } from 'vue'
const { proxy } = getCurrentInstance()
const registerForm = ref({
  username: '',
  email: '',
  password: '',
  confirmPassword: ''
})
const validatePassword = (rule, value, callback) => {
  if (value !== registerForm.value.password) {
    callback(new Error('密码不匹配'))
  } else {
    callback()
  }
}

const register = () => {
  console.log('注册信息:', registerForm.value)
  // 这里可以添加注册逻辑，例如发送请求到后端
  proxy.$refs.registerFormRef.validate(valid => {
    if (!valid) {
      return
    }
  })
}
</script>

<style lang="scss" scoped>
.register-container {
  width: 400px;
  margin: 100px auto;
  padding: 20px;
  border: 1px solid #dcdfe6;
  border-radius: 5px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  .elForm {
    display: flow-root;
    .registerBut {
      float: right;
    }
  }
}
.login-link {
  margin-top: 20px;
}
</style>
